import {Component} from '@angular/core';
import {App, NavController} from 'ionic-angular';

import {addTrenchPage} from './addTrench/addTrench';
//引入产品信息页面
import {conProductPage} from "./conProductPage/productPage";
import {ModalController} from 'ionic-angular';

//  http
import {Http,Headers} from '@angular/http';
import {interfaceUrls} from '../../provider/serverUrls';	//没有真实数据暂时不需要引入接口
import 'rxjs/add/operator/toPromise';
import 'rxjs/add/operator/timeout';
//获取从服务传递过来的收货渠道信息
import {services} from '../../providers/service';
import {UserService} from "../../providers/user-service";
import {AppPopup} from "../../util/popup";
import {UserLogin} from "../../modules/app-user/user-login/user-login";
@Component({
  selector: 'page-contact',
  templateUrl: 'contact.html'
})
export class ContactPage {

    dealerInfo={};
    items = [];       //当前经销商产品
    fristProName;   //第一个经销商产品
    fristProId;     //第一个经销商产品ID用来查询第一个发货产品渠道
    items3 = [];


    showTrench = true;   //切换到收货渠道下方添加按钮消失
    items2 = []; //经销商发货渠道
    param = {};
    param2 = {
        "keyword": "", "productId": ""
    };
    param3 = {
        "keyword": "", "productId": ""
    };
    pet: string = "发货渠道";
    pageNo = 1;     //当前页
    pageSize = 5;  //每页条数
    count = 0;      //计算总页数
    public headers = new Headers({'Content-Type': 'application/json;chartset=utf-8'});

    constructor(public navCtrl: NavController,
                public http: Http,
                private userServ: UserService,
                private popup: AppPopup,
                private app: App,
                public modalCtrl: ModalController,
                public services: services,) {
    }
 //添加经销商账户
    addTrench() {
        this.navCtrl.push(addTrenchPage);
    }

    delar() {
        this.showTrench = true;    //添加发货渠道按钮出现
    }

    showBtn() {
        this.showTrench = false;
    }

    ionViewWillEnter() {
        this.userServ.getPersonInfo()
            .then(() => {
            })
            .catch(err => {
                console.error("用户详情获取失败：", err);
                if (err.errorMassage == "未登录或登录超时！") {
                    this.popup.alert(err.errorMassage)
                        .then(() => {
                            this.app.getRootNav().setRoot(UserLogin);
                        });
                }
            });
        console.info("==================进入经销商列表页面================");
        //input输入框中的产品数据、此处产品信息多次用到因此放到服务中
        this.http
            .post(interfaceUrls.productList, JSON.stringify(this.param), {headers: this.headers})
            .timeout(2000)
            .toPromise()
            .then(response => {
                let rs = response.json();
                if(rs.resultStatus != "success"){
                    this.popup.alert(rs.errorMassage);
                    return;
                }
                console.info(response.json().infoData, "用户all产品多处用到因此放到服务中++");
                this.items = response.json().infoData;
                this.services.productList02 = this.items; //放到服务中

                console.log(this.items[0].name, "++++++++++++++++++++++++第一个产品信息", this.items[0].id, "第一个产品ID+++++++++++++");

                this.fristProName = this.items[0].name;
                this.fristProId = this.items[0].id;

                // 第一个产品发货货渠道查询，默认显示第一条
                this.http
                    .post(`${interfaceUrls.dealerDeliver}?pageNo=${this.pageNo}&pageSize=${this.pageSize}`, this.param = {
                        "productId": this.fristProId
                    })
                    .timeout(2000)
                    .toPromise()
                    .then(res => {
                        let rs = response.json();
                        if(rs.resultStatus != "success"){
                            this.popup.alert(rs.errorMassage);
                            return;
                        }
                        console.info(this.param, "查询发货渠道传递的参数默认显示第一条++++")
                        this.items2 = res.json().infoData.items;
                        console.info(this.items2, "根据第一个ID查询到的发货渠道++");
                        // this.services.items2 = res.json().infoData;
                        this.count = Math.ceil(res.json().infoData.count / this.pageSize);
                        // console.info(this.services.items2)

                    })
                    .catch(err => {
                        console.log('err');
                    });

                // 第一个产品收货渠道查询，默认显示第一条
                this.http
                    .post(interfaceUrls.dealerReceive, this.param = {
                        "productId": this.fristProId
                    })
                    .timeout(2000)
                    .toPromise()
                    .then(resp => {
                        let rs = response.json();
                        if(rs.resultStatus != "success"){
                            this.popup.alert(rs.errorMassage);
                            return;
                        }
                        console.info("收货渠道查询", resp.json().infoData.items, "收货渠道查询默认显示第一条++++++", this.param);
                        // console.info("收货渠道公司名称", resp.json().infoData.items[0].companyName);

                        this.items3 = resp.json().infoData.items;
                        // console.info("收货渠道", this.services.items3)

                    })
                    .catch(err => {
                        console.log('err');
                    });
                //
            })
            .catch(err => {
                console.log('err', err);
            });

    }

    openModal(showDealer) {
        let modal = this.modalCtrl.create(conProductPage, showDealer);
        modal.onDidDismiss(data => {
            console.info("模态框消失的时候传的数据：openModal,", data);
            if(!data) {
                return;
            }
            this.fristProName = data.name;
            this.fristProId = data.id;
            this.http
                .post(interfaceUrls.dealerDeliver, {"productId": data.id})
                .timeout(2000)
                .toPromise()
                .then(response => {
                    let data = response.json().infoData.items;
                    console.info(this.param, "查询发货渠道传递的参数", data, "查询发货渠道接收的数据");
                    this.items2 = data;
                })
                .catch(err => {
                    console.log('err');
                });
            // 根据产品收货渠道查询，
            this.http
                .post(interfaceUrls.dealerReceive, {"productId": data.id})
                .timeout(2000)
                .toPromise()
                .then(response => {
                    console.info("收货渠道查询到的数据", "收货渠道发送的ID参数", this.param);
                    this.items3 = response.json().infoData.items;
                })
                .catch(err => {
                    console.log('err');
                });
        });
		modal.present();
	}

    //下拉刷新
    doRefresh(refresher) {
        //发货渠道下拉刷新
        if (!this.services.protectId0) {
            this.pageNo = 1;
            this.http
                .post(`${interfaceUrls.dealerDeliver}?pageNo=${this.pageNo}&pageSize=${this.pageSize}`, this.param = {
                    "productId": this.fristProId
                })
                .timeout(2000)
                .toPromise()
                .then(response => {
                    console.info(this.param, "查询发货渠道传递的参数");
                    console.info(response.json().infoData.items);
                    this.items2 = response.json().infoData.items;
                    refresher.complete();	//刷新完成

                })
                .catch(err => {
                    console.log('err');
                });
            //收货渠道下拉刷新
            this.pageNo = 1;
            this.http
                .post(`${interfaceUrls.dealerReceive}?pageNo=${this.pageNo}&pageSize=${this.pageSize}`, this.param = {
                    "productId": this.fristProId
                })
                .timeout(2000)
                .toPromise()
                .then(response => {
                    console.info(this.param, "查询收货渠道传递的参数");
                    console.info(response.json().infoData.items);
                    this.items3 = response.json().infoData.items;
                    refresher.complete();	//刷新完成

                })
                .catch(err => {
                    console.log('err');
                });

        } else {
            this.pageNo = 1;
            this.http
                .post(`${interfaceUrls.dealerDeliver}?pageNo=${this.pageNo}&pageSize=${this.pageSize}`, this.param = {
                    "productId": this.services.protectId0
                })
                .timeout(2000)
                .toPromise()
                .then(response => {
                    console.info(this.param, "查询发货渠道传递的参数");
                    console.info(response.json().infoData.items);
                    this.items2 = response.json().infoData.items;
                    refresher.complete();	//刷新完成

                })
                .catch(err => {
                    console.log('err');
                });
            //收货渠道下拉刷新
            this.pageNo = 1;
            this.http
                .post(`${interfaceUrls.dealerReceive}?pageNo=${this.pageNo}&pageSize=${this.pageSize}`, this.param = {
                    "productId": this.services.protectId0
                })
                .timeout(2000)
                .toPromise()
                .then(response => {
                    console.info(this.param, "查询收货渠道传递的参数");
                    console.info(response.json().infoData.items);
                    this.items3 = response.json().infoData.items;
                    refresher.complete();	//刷新完成

                })
                .catch(err => {
                    console.log('err');
                });
        }
    }

    //上拉加载
    doInfinite(infiniteScroll) {
        console.info("加载事件触发...")
        console.log(this.count, this.pageNo);
        if (this.count > this.pageNo) {
            this.pageNo += 1;

            this.http
                .post(`${interfaceUrls.dealerDeliver}?pageNo=${this.pageNo}&pageSize=${this.pageSize}`, JSON.stringify(this.param), {headers: this.headers})
            .timeout(2000)
            .toPromise()
            .then(response => {
                console.info(response.json().infoData.items);
                // this.items = response.json().infoData.items;
                this.items2 = this.items2.concat(response.json().infoData.items);
                console.info(this.items2, "加载的数据........")
                infiniteScroll.complete();	//加载完成

            })
            .catch(err => {
                console.log('err');
            });
        } else {
            infiniteScroll.complete();
        }//加载完成
    }
}
